var ajax = true;

$('#fileToUpload').live('change', function(){
	var ex = $(this).val().split('.').pop();
	if(ex!='jpg' && ex!='png' && ex!='gif'){
		alert('Вы загрузили файл не правильного формата. Поддерживается jpg, png, gif формат.');
		return false;
	}
	$("#popup").removeClass('hidden').addClass('allScreen');
	//starting setting some animation when the ajax starts and completes
	$.ajaxFileUpload({
		url: $(this).parents('form').attr('action'), 
		secureuri:false,
		fileElementId:'fileToUpload',
		dataType: 'json',
		success: function (data){
			$("#popup").addClass('hidden').removeClass('allScreen');
			$('body').css('overflow','auto');
			var href = window.location.hash.substring(1);
			if(href=='#' || href==''){
				href='/';
			}
			$.ajax({
				url: href,
				dataType: "html",
				context: document.body,
				beforeSend: function (  ) {
					$('.loading').show(0);
				},
				data: "ajax=true",
				type: "GET",
				success: function(data) {
					var content = data.match(/<div id="layout"[^>]*>([\w|\W]*)<\/div>/im);
					$("#layout").empty().append($(content[1]));
				}
			});
		}
	})
	return false;
});
$('#fileToUploadPopup').live('change', function(){
	var ex = $(this).val().split('.').pop();
	if(ex!='jpg' && ex!='png' && ex!='gif'){
		alert('Вы загрузили файл не правильного формата. Поддерживается jpg, png, gif формат.');
		return false;
	}
	$("#popup").find('.popup_body').hide(0);
	$("#popup").removeClass('hidden').addClass('allScreen');
	//starting setting some animation when the ajax starts and completes
	$.ajaxFileUpload({
		url: $(this).parents('form').attr('action'), 
		secureuri:false,
		fileElementId:'fileToUploadPopup',
		dataType: 'json',
		success: function (data){
			$("#popup").addClass('hidden').removeClass('allScreen');
			$('body').css('overflow','auto');
			var html = "<div class='one_image'>" +
							"<div class='image_x_wrap'><div class='image_x'></div></div>" +
							"<img width='180' class='material_img' src='"+ data.path + data.img +"'/>" +
							"<input type='hidden' name='images[]' value='"+ data.msg +"' class='images' />"+
						"</div>";
			$('.current_attachment').after(html);
			$('.current_attachment').remove();
		}
	})
	return false;
});
$('#fileToUploadPopupAudio').live('change', function(){
	 if($(this).val().split('.').pop()!='mp3'){
		alert('Вы загрузили файл не правильного формата. Поддерживается mp3 формат.');
		return false;
	}
	$("#popup").find('.popup_body').hide(0);
	$("#popup").removeClass('hidden').addClass('allScreen');
	//starting setting some animation when the ajax starts and completes
	$.ajaxFileUpload({
		url: $(this).parents('form').attr('action'), 
		secureuri:false,
		fileElementId:'fileToUploadPopupAudio',
		dataType: 'json',
		success: function (data){
			$("#popup").addClass('hidden').removeClass('allScreen');
			$('body').css('overflow','auto');
			var html = "<div class='one_image one_music'>" +
							"<div class='u_audio__item'>"+
								"<div class='play_btn'></div>"+
								"<a href='#' data-src='/upload/audio/"+data.file+"' class='u_audio__name'>"+data.name+"</a>"+
							"</div>"+
							"<input type='hidden' name='musics[]' value='"+ data.msg +"' class='musics' />"+
						"</div>";
			$('.current_attachment').after(html);
			$('.current_attachment').remove();
		}
	})
	return false;
});
$('#fileToUploadAudio').live('change', function(){
	if($(this).val().split('.').pop()!='mp3'){
		alert('Вы загрузили файл не правильного формата. Поддерживается mp3 формат.');
		return false;
	}
	$("#popup").removeClass('hidden').addClass('allScreen');
	$('body').css('overflow','auto');
	var form = $(this).parents('form');
	//starting setting some animation when the ajax starts and completes
	$.ajaxFileUpload({
		url: form.attr('action'), 
		secureuri:false,
		fileElementId:'fileToUploadAudio',
		dataType: 'json',
		success: function (data){
			$("#audio-form").removeClass('hidden');
			form.addClass('hidden');
			$("#audio-form #Music_id").val(data.msg);
			$("#audio-form #defoultMusicName").val(data.music_name);
			$("#popup").addClass('hidden').removeClass('allScreen');
		}
	})
	return false;
});
$('#fileToUploadGroupAvatar').live('change', function(){
	var ex = $(this).val().split('.').pop();
	if(ex!='jpg' && ex!='png' && ex!='gif'){
		alert('Вы загрузили файл не правильного формата. Поддерживается jpg, png, gif формат.');
		return false;
	}
	$("#popup").removeClass('hidden').addClass('allScreen');
	$('body').css('overflow','auto');
	var form = $(this).parents('form');
	//starting setting some animation when the ajax starts and completes
	$.ajaxFileUpload({
		url: form.attr('action'), 
		secureuri:false,
		fileElementId:'fileToUploadGroupAvatar',
		dataType: 'json',
		success: function (data){
			form.addClass('hidden');
			$("#groups-form #Groups_avatar").val(data.msg);
			$("#groups-form #defoultMusicName").val(data.music_name);
			$("#popup").addClass('hidden').removeClass('allScreen');
		}
	})
	return false;
});
$('#fileToUploadUrl').live('change', function(){
	var ex = $(this).val().split('.').pop();
	if(ex!='jpg' && ex!='png' && ex!='gif'){
		alert('Вы загрузили файл не правильного формата. Поддерживается jpg, png, gif формат.');
		return false;
	}
	$("#popup").removeClass('hidden').addClass('allScreen');
	$('body').css('overflow','auto');
	var form = $(this).parents('form');
	//starting setting some animation when the ajax starts and completes
	$.ajaxFileUpload({
		url: form.attr('action'), 
		secureuri:false,
		fileElementId:'fileToUploadUrl',
		dataType: 'json',
		success: function (data){
			$("#groups-urls-form").removeClass('hidden');
			form.addClass('hidden');
			$("#groups-urls-form #GroupsUrls_id").val(data.msg);
			$("#groups-urls-form #EventsUrls_id").val(data.msg);
			$("#popup").addClass('hidden').removeClass('allScreen');
		}
	})
	return false;
});
// загрузка видео в попапе
$('form.uploadVideoPopup').live('submit', function() {
	var form = $( this ),
	term = '{';
	form.find( 'input, textarea, select' ).each(function(){
		if($(this).attr('type') == 'checkbox'){
			if($(this).is(':checked')){
				term = term + '"' + $(this).attr('name') + '": "' + $(this).val() + '", ';
			}
		}else{
			term = term + '"' + $(this).attr('name') + '": "' + $(this).val() + '", ';
		}		
	}),
	href = form.attr( 'action' ),
	resultUrl = form.attr( 'rel' );
	term = term.slice(0, -2) + '}';
	var dataJson = $.parseJSON(term);
	$.ajax({
		url: href,
		type: 'POST',
		beforeSend: function (  ) {
		    $('.loading').show(0);
		},
		data: dataJson,
		success: function(data) {
			$("#popup").addClass('hidden').removeClass('allScreen');
			$('body').css('overflow','auto');
			$('.current_attachment').after(data);
			$('.current_attachment').remove();
		},
		error: function (data) {
			$('#warningMsg').text(data).show(0);		        
		}
	});
	return false;
});

$(function() { 
    // Setup the player to autoplay the next track
	var a = audiojs.createAll({
		trackEnded: function() {
			var next = $('.u_audio_player .u_audio__item.playing').next();
			if (!next.length) next = $('.u_audio_player .u_audio__item').first();
			$('.audiojs').appendTo(next);
			$('.volumePanel').appendTo(next);
			next.addClass('playing').siblings().removeClass('playing');
			audio.load($('a', next).attr('data-src'));
			audio.play();
		}
	});
	var audio = a[0];
    audiojs.events.ready(function() {
        $('.volume_icon').live('click',function(e){
    		if($(this).hasClass('mute')){
    			$('#audioSlider').slider( "value" , 1 );
    			$(this).removeClass('mute');
    			audio.setVolume(1);
    		} else {
    			$('#audioSlider').slider( "value" , 0 );
    			$(this).addClass('mute');
    			audio.setVolume(0);
    		}
    		e.preventDefault();
			return false;
    	});
        
    });
	// Load in a track on click
	$('.u_audio_player .u_audio__item .u_audio_track, .u_audio__item .play_btn').live('click', function(e) {
		e.preventDefault();
	  	$('.u_audio__item').removeClass('playing');
	  	$(this).parents('.u_audio__item').addClass('playing').siblings().removeClass('playing');
	  	$('.audiojs').appendTo($(this).parents('.u_audio__item'));
	  	$('.volumePanel').appendTo($(this).parents('.u_audio__item'));
	  	if($(this).parents('#music').length==0){
	  		//move to music box
	  		var parent = $(this).parents('.u_audio_player').parent();
	  		//$('#music')./*empty().*/addClass($(parent).attr('class'));
	  		$('#music .musicInner').html('');
		  	$(this).parents('.u_audio_player').appendTo('#music .musicInner');
		  	parent.html('<p class="music_notify">Музыка добавлена в Ваш плеер</p>')
		  	$('#music').show(0)
		}
	  	var current = $(this);
	  	setTimeout(
	  		function() {
	  		  	audio.load(current.parents('.u_audio__item').find('a').attr('data-src'));
	  			audio.play();
	  		}, 
	  		1500
	  	);
	});

	$('.clearPlayer').live('click', function(){
		$('#music .u_audio__item').not('.playing').remove();
		return false;
	});
	$('.closePlayer').live('click', function(){
		$('#music .u_audio__item').not('.playing').remove();
		$('#music').hide();
		audio.pause();
		return false;
	});
	
	$('#audioSlider').slider({
	    orientation: "horizontal",
	    value: 1,
	    min: 0,
	    max: 1,
	    range: 'min',
	    animate: true,
	    step: .1,
	    slide: function(e, ui) {
	       audio.setVolume(ui.value);
	    }
	});
});
/* ajax functionality */
function strToJson(str) {
  eval("var x = " + str + ";");
  return JSON.stringify(x);
}
function changeTitle(val){
	document.title = val;
}
$(window).load(function(){
	$('.flds_border_inside textarea').live({
		keypress: function(){
	        var hard_lines = 0;  
	        var cof = 1;
	        var str = $(this).val().split("\n");  
	        hard_lines = str.length;  
	        
	        var letter_width =  $(this).clientHeight/ $(this).rows*cof/100; // приблизительная ширина одной буквы в пикселях  
	        var chars_in_line =  $(this).clientWidth/letter_width; //сколько букв в строке  
	  
	        var lines = 0;  
	        var temp = 0;  
	        for(i=0; i<=(hard_lines-1); i++){ //hard_lines-1 = количество элементов в массиве  
	            temp = str[i].length / chars_in_line;  
	            if(temp>0) lines += temp;  
	        }     
	  
	        var new_rows = lines+hard_lines;  
	        $(this).css('height', new_rows*20);//чтобы не прыгало  
		},
		keyup: function(){
	        var hard_lines = 0;  
	        var cof = 1;
	        var str = $(this).val().split("\n");  
	        hard_lines = str.length;  
	        
	        var letter_width =  $(this).clientHeight/ $(this).rows*cof/100; // приблизительная ширина одной буквы в пикселях  
	        var chars_in_line =  $(this).clientWidth/letter_width; //сколько букв в строке  
	  
	        var lines = 0;  
	        var temp = 0;  
	        for(i=0; i<=(hard_lines-1); i++){ //hard_lines-1 = количество элементов в массиве  
	            temp = str[i].length / chars_in_line;  
	            if(temp>0) lines += temp;  
	        }     
	  
	        var new_rows = lines+hard_lines;  
	        $(this).css('height', new_rows*20);//чтобы не прыгало  
		},
		change: function(){
	        var hard_lines = 0;  
	        var cof = 1;
	        var str = $(this).val().split("\n");  
	        hard_lines = str.length;  
	        
	        var letter_width =  $(this).clientHeight/ $(this).rows*cof/100; // приблизительная ширина одной буквы в пикселях  
	        var chars_in_line =  $(this).clientWidth/letter_width; //сколько букв в строке  
	  
	        var lines = 0;  
	        var temp = 0;  
	        for(i=0; i<=(hard_lines-1); i++){ //hard_lines-1 = количество элементов в массиве  
	            temp = str[i].length / chars_in_line;  
	            if(temp>0) lines += temp;  
	        }     
	  
	        var new_rows = lines+hard_lines;  
	        $(this).css('height', new_rows*20);//чтобы не прыгало  
		}
	});  

	if(ajax){
		$('.search_block form, form#main_search, form#groups-urls-form, form#groups-form, form#contact-form, form#buzz_message, form#cat_search, form#albums-form, form#audio-form, form#video-form').live('submit', function() {
			var form = $( this ),
			term = '{';
			form.find( 'input, textarea, select' ).each(function(){
				if($(this).attr('type') == 'checkbox'){
					if($(this).is(':checked')){
						term = term + '"' + $(this).attr('name') + '": "' + $(this).val() + '", ';
					}
				}else{
					term = term + '"' + $(this).attr('name') + '": "' + $(this).val() + '", ';
				}
			}),
			/*
			form.find( 'textarea' ).each(function(){
				term = term + '"' + $(this).attr('name') + '": "' + $(this).val() + '", ';
			}),*/
			href = form.attr( 'action' ),
			resultUrl = form.attr( 'rel' );
			term = term.slice(0, -2) + '}';
			var dataJson = $.parseJSON(term);
			$.ajax({
				url: href,
				type: 'POST',
				beforeSend: function (  ) {
				    $('.loading').show(0);
				},
				data: dataJson,
				success: function(data) {
					var content = data.match(/<div id="layout"[^>]*>([\w|\W]*)<\/div>/im);
					var title = data.match(/<title>(.*?)<\/title>/);
					if(title!=undefined) changeTitle(title[1]);
				    $("#layout").empty();
				    $("#layout").append($(content[1]));
					window.location.hash = resultUrl;
					$('.loading').hide(0);
					var params = {
						visRows: 5,
						changedEl: "select"
					}
					cuSel(params);
				},
				error: function (data) {
					$('#warningMsg').text(data.status + ' - ' + data.statusText).show(0);		        
				}
			});
			return false;
		});
		if(window.location.hash != null) {
			var href = window.location.hash.substring(1);
			if($('#backBtn').attr('href')!=href && href!=''){
				$('#backBtn').attr('href', href);
			}
			if(href!='#' && href!=''){
				$.ajax({
					url: href,
					dataType: "html",
					context: document.body,
					beforeSend: function (  ) {
					    $('.loading').show(0);
					},
					data: "ajax=true",
					type: "GET",
					success: function(data) {
						var content = data.match(/<div id="layout"[^>]*>([\w|\W]*)<\/div>/im);
						var title = data.match(/<title>(.*?)<\/title>/);
						changeTitle(title[1]);
					    $("#layout").empty().append($(content[1]));
						window.location.hash = href;
						initAutocomplete();
						var params = {
							visRows: 5,
							changedEl: "select"
						}
						cuSel(params);
						//$('.loading').hide(0);
					}
				});
			}
		}
	}
});

$(document).ready(function(){
	/*$('.inviteLink').live('click', function(){
		$(this).html('Приглашения отправленно');
	});*/
	$('#birthday').datepicker();
	$('.add_files_fld .green_btn').live('click', function() {
		$('.fileUpload:first').click();
		return false;
	});
	$('.saveForm').live('click', function() {
		$('.form form').submit();
	});
	if(ajax){
		$('a.u_buzz_link.l1, .cat_head_members a, .search_more_link, .ajaxLink, .ajaxLinks a, .video_list_item_hidden a:first, .u_buzz_item_l a, .profileName, .u_friend a, .popup_data_u a, #logo, .albums a, .u_cat_head a, #backBtn, .cat_list .album_list_item a, .f_dialog_item .u_buzz_item_l a, .f_dialog_item .u_buzz_item_r a, .f_dialog_item .f_dialog_item_text a, .user_action_menu a, .f_list_name a, .f_list_img, .cat_head a, .user_action_l a, .operations a:not(.saveForm)').live('click', function() {
			var href = $(this).attr('href');
			$('#warningMsg').hide(0);
			if($('#backBtn').attr('href')!=href && href!=''){
				$('#backBtn').attr('href', window.location.hash.substring(1)).show(0);
			}
			if(href=='#' || href==''){
				href='/';
			}
			$.ajax({
				url: href,
				dataType: "html",
				context: document.body,
				beforeSend: function (  ) {
				    //$('.loading').show(0);
				},
				data: "ajax=true",
				type: "GET",
				success: function(data) {
					var content = data.match(/<div id="layout"[^>]*>([\w|\W]*)<\/div>/im);
					var title = data.match(/<title>(.*?)<\/title>/);
					changeTitle(title[1]);
				    $("#layout").empty().append($(content[1]));
				    $('#popup').addClass('hidden');
					$('#popup .popup_reduser .popup_body').remove();
					$('body').css('overflow','auto');
					$('.current_attachment').remove();
					window.location.hash = href;
					$(document).scrollTop(0);
					initAutocomplete();
					//$('.loading').hide(0);
					// �������
					var params = {
							visRows: 5,
							changedEl: "select"
						}
					cuSel(params);
				},
				error: function (data) {
					$('#warningMsg').text(data.status + ' - ' + data.statusText).show(0);		        
				}
			});
			return false;
		});
		$('.removeLink').live('click', function() {
			var crnt = window.location.hash;
			var href = $(this).attr('href');
			if(href=='#' || href==''){
				href='/';
			}
			$.ajax({
				url: href,
				dataType: "html",
				context: document.body,
				data: "ajax=true",
				type: "GET",
				success: function(data) {
					$.ajax({
						url: crnt.substring(1),
						dataType: "html",
						context: document.body,
						beforeSend: function (  ) {
							//$('.loading').show(0);
						},
						data: "ajax=true",
						type: "GET",
						success: function(data) {
							var content = data.match(/<div id="layout"[^>]*>([\w|\W]*)<\/div>/im);
							$("#layout").empty().append($(content[1]));
							$('#popup').addClass('hidden');
							$('#popup .popup_reduser .popup_body').remove();
							$('body').css('overflow','auto');
							$('.current_attachment').remove();
							window.location.hash = crnt;
							$(document).scrollTop(0);
						}
					});
				}
			});
			return false;
		});
	}
});
function leftSidebar(){
	//get width of next and prev
	var widthBtn = (($('body').width()-860)/2)-114;
//	$('#backBtn, #topBtn').css('left', widthBtn<=0 ? 5 : widthBtn);
//	$('#music').css('left', widthBtn<=170 ? 10 : widthBtn-140);
	$('#backBtn, #topBtn').css('left', widthBtn);
	$('#music').css('left', widthBtn-0);
	return widthBtn;
}
$(window).resize(function() {
	leftSidebar();
});
$(document).ready(function() {
	
	$('#topBtn').live('click', function(){
		$('body, html').animate({scrollTop: $("body").offset().top}, 500);
		return false;
	});
	$(window).scroll(function () {
		if ($(this).scrollTop() > 100) {
            $('#topBtn').fadeIn();
        } else {
            $('#topBtn').fadeOut();
        }
	});
	var widthBtn = leftSidebar();
	// �������
	var params = {
		visRows: 5,
		changedEl: "select"
	}
	cuSel(params);
	$('.select_block').live('click',function(){
		if($(this).find('.cusel').hasClass('cuselOpen')) {
			$('.select_block ').css('z-index','1');
			$(this).css('z-index','2');
		}
		else {
			$('.select_block').css('z-index','1');
			$(this).css('z-index','1');
		}
	});
	// �������� ������
	$('.albums .u_media_nav_prev').live('click', function(){
		swipeAlbumsL();
	});
	$('.albums .u_media_nav_next').live('click', function(){
		swipeAlbumsR();
	});
	$('.video .u_media_nav_prev').live('click', function(){
		swipeVideoL();
	});
	$('.video .u_media_nav_next').live('click', function(){
		swipeVideoR();
	});
	// ������ � ���������
	$('.search_fld input:text, .user_status_fld_l input:text, textarea').live('click', function(){
		if ($(this).attr('placeholder') == undefined) {
			if (this.value == this.defaultValue) {
				this.value = '';
			}		    
		}
	});
	$('.search_fld input:text, .user_status_fld_l input:text, textarea').live('blur', function(){
		if ($(this).attr('placeholder') == undefined) {
			if (this.value == '') {
				this.value = this.defaultValue;
			}		    
		}		
	});
	// ��������� � ������
	$('.user_action_item').live({
        mouseenter:
           function(){
        		$(this).addClass('hover').find('.user_action_item_tooltip').removeClass('hidden');
           },
        mouseleave:
           function()
           {
        		$(this).removeClass('hover').find('.user_action_item_tooltip').addClass('hidden');
           }
       }
    );	
	$('.buzz_adds_item').live({
        mouseenter:
           function(){
        		$(this).addClass('hover').find('.user_action_item_tooltip').removeClass('hidden');
           },
        mouseleave:
           function()
           {
        		$(this).removeClass('hover').find('.user_action_item_tooltip').addClass('hidden');
           }
       }
    );		
	$('.u_buzz_link').live({
        mouseenter:
           function(){
        		$(this).addClass('hover').find('.user_action_item_tooltip').removeClass('hidden');
           },
        mouseleave:
           function()
           {
        		$(this).removeClass('hover').find('.user_action_item_tooltip').addClass('hidden');
           }
       }
    );	

	$('.u_buzz_item').live({
        mouseenter:
           function(){
        		$(this).find('.u_buzz_link_block').removeClass('hidden');
           },
        mouseleave:
           function()
           {
        		$(this).find('.u_buzz_link_block').addClass('hidden');
           }
       }
    );
	$('.player_dot').hover(
		function(){
			$(this).find('.user_action_item_tooltip').removeClass('hidden');
		},
		function(){
			$(this).find('.user_action_item_tooltip').addClass('hidden');
		}
	);
	$('.u_audio__item').hover(
		function(){
			$(this).css('z-index','2').find('.player_block_links').removeClass('hidden');
			$(this).find('.player_text').removeClass('invisible');
		},
		function(){
			$(this).css('z-index','1').find('.player_block_links').addClass('hidden');
			$(this).find('.player_text').addClass('invisible');
		}
	);
	$('.f_dialog_item').live({
        mouseenter:
           function(){
        		$(this).css('z-index','2').find('.u_buzz_link_block').removeClass('hidden');
           },
        mouseleave:
           function()
           {
        		$(this).css('z-index','1').find('.u_buzz_link_block').addClass('hidden');
           }
       }
    );
	/*
	$('.u_media').live('hover',
		function(){
			$(this).find('.mask.hover, .links').removeClass('hidden');
		},
		function(){
			$(this).find('.mask.hover, .links').addClass('hidden');
		}
	);
	*/
	// ��������
	$('.checkbox_block div, .checkbox_block label').live('click', function() {
		var parent = $(this).parents('.checkbox_block').first();
		if( parent.hasClass('checked') ) {
			parent.removeClass('checked');
			parent.find('input').removeAttr('checked');
		}
		else {
			parent.addClass('checked');
			parent.find('input').attr('checked','checked');
		}
	});
	// �����
	$('form').change(function(){
		var id = $(this).find('.radio_block .radio_item:checked').attr('id');
		var parent = $('#'+id).parents('.radio_block');
		parent.addClass('checked');
		parent.find('input.radio_item').attr('checked','checked');
		
		$(this).find('.radio_item').not('#'+id).parents('.radio_block').each(function(){
			$(this).removeClass('checked');
			$(this).find('input.radio_item').removeAttr('checked');
		});
	});
	$('.radio_block div, .radio_block label').live('click', function(){
		var id = $(this).siblings('.radio_item').attr('id');
		var parent = $('#'+id).parents('.radio_block');
		parent.addClass('checked');
		parent.find('input.radio_item').attr('checked','checked');
		
		$(this).parents('form').find('.radio_item').not('#'+id).parents('.radio_block').each(function(){
			$(this).removeClass('checked');
			$(this).find('input.radio_item').removeAttr('checked');
		});
	});
	// �����
	$('.uploadAvatar').live('click', function(){
		try{
			$.ajax({
				url: $(this).attr('href'),
				type: "GET",
				success: function(data) {
					$('#popup .popup_reduser').html(data);
					$('#popup').removeClass('hidden').addClass('allScreen');
					$('body').css('overflow','hidden');
				}
			});
		} catch(e) {
			alert("Выпало "+e.name)
		}
		return false;
	});
	$('.video_list_item a, .video a, .video_list_item_hidden .u_media_nav_name').live('click', function(){
		try{
			$.ajax({
				url: $(this).attr('href'),
				type: "GET",
				success: function(data) {
					$('#popup .popup_reduser').html(data);
					$('#popup').removeClass('hidden');
					$('body').css('overflow','hidden');
				}
			});
		} catch(e) {
			alert("Выпало "+e.name)
		}
		return false;
	});
	$('.photoBg, .photoView, .prev, .next').live('click',function(){
		try{
			if($(this).hasClass('photoBg')){
				var el = $(this);
			}
			$.ajax({
				url: $(this).attr('href'),
				type: "GET",
				success: function(data) {
					$('#popup .popup_reduser').html(data);
					$('.prev').css({'left' : -widthBtn, 'width' : widthBtn});
					$('.next').css({'right' : -widthBtn, 'width' : widthBtn});
					var h = $('body').height();
					$('.popup_content img').css({'max-height' : h-150});
					$('#popup').removeClass('hidden');
					$('body').css('overflow','hidden');
					if(el != undefined && el.parent('.cat_list').length==0){
						$('.prev, .next, .popup_head a').hide(0);
					};
					$('.popup_content img').load(function(){
						if(h>$('#popup #fade').height()){$('#popup').addClass('allScreen')}
					});
				}
			});
		} catch(e) {
			alert("Выпало "+e.name)
		}
		return false;
	});
	$('#popup_close').live('click',function(){
		$('#popup').addClass('hidden').removeClass('allScreen');
		$('#popup .popup_reduser .popup_body').remove();
		$('body').css('overflow','auto');
		$('.current_attachment').remove();
	});
	$('#fade').live('click',function(event){
		if(event.target.id == 'fade' || event.target.className =='popup_reduser' ){
			$('#popup').addClass('hidden').removeClass('allScreen');
			$('#popup .popup_reduser .popup_body').remove();
			$('body').css('overflow','auto');
			$('.current_attachment').remove();
		}
	});
	// ������ ������... 
	$('#more_info').live('click', function(){
		$(this).parents('.ovh').prev('.user_info_table').find('tr.hidden').slideDown(300);
		$(this).addClass('hidden').siblings('div').removeClass('hidden');
	});
	$('#less_info').live('click', function(){
		$(this).parents('.ovh').prev('.user_info_table').find('tr.hidden').slideUp(300);
		$(this).addClass('hidden').siblings('div').removeClass('hidden');
	});
	$('#more_message, .more_message').click(function(){
		$(this).parents('.ovh').prev('.user_block').find('.u_buzz_item.hidden').slideDown(300);
		$(this).addClass('hidden').siblings('div').removeClass('hidden');
	});
	$('#less_message, .less_message').click(function(){
		$(this).parents('.ovh').prev('.user_block').find('.u_buzz_item.hidden').slideUp(300);
		$(this).addClass('hidden').siblings('div').removeClass('hidden');
	});
	// ����
	$('.u_tab').live('click', function(){
		var id = $(this).attr('id')
		$(this).addClass('curr').siblings('.u_tab').removeClass('curr');
		$('#'+id+'_').removeClass('hidden').siblings('.tab').addClass('hidden');
		$('.cat_head').addClass('hidden');
		$('#'+id+'_').find('.cat_head').removeClass('hidden');
		//JScrollHeightDouble();
	});
	
});
$(window).load(function() {
	
});
// ������������ ������
function swipeAlbumsL() {
	var img = $('.albums').find('.u_media');
	var curr_img = null;
	img.each(function(){
		if( !$(this).hasClass('hidden') ){
			curr_img = $(this)
		}
	});
	var id = curr_img.attr('id');
	var arr_id = id.split('_');
	var curr_id = arr_id[0];
	var curr_num = arr_id[1]*1;
	var next_num = curr_num-1;
	if(next_num<1  ) {
		next_num = img.length;
	}
	//alert('#'+curr_id+'_'+next_num+'_')
	$('#'+curr_id+'_'+next_num).removeClass('hidden').siblings('.u_media').addClass('hidden');
	$('#'+curr_id+'_'+next_num+'_').removeClass('hidden').siblings('.u_media_nav_name').addClass('hidden');
	//$('#'+curr_id+'_'+next_num).addClass('curr').siblings('.switch').removeClass('curr');
};
function swipeAlbumsR() {
	var img = $('.albums').find('.u_media');
	var curr_img = null;
	img.each(function(){
		if( !$(this).hasClass('hidden') ){
			curr_img = $(this)
		}
	});
	var id = curr_img.attr('id');
	var arr_id = id.split('_');
	var curr_id = arr_id[0];
	var curr_num = arr_id[1]*1;
	var next_num = curr_num+1;
	if( $('#'+curr_id+'_'+next_num+'_').length<1 ) {
		next_num = 1;
	}
	
	//alert('#'+curr_id+'_'+next_num+'_')
	$('#'+curr_id+'_'+next_num).removeClass('hidden').siblings('.u_media').addClass('hidden');
	$('#'+curr_id+'_'+next_num+'_').removeClass('hidden').siblings('.u_media_nav_name').addClass('hidden');
	//$('#'+curr_id+'_'+next_num+'__').addClass('curr').siblings('.switch').removeClass('curr');
};
// ������������ ������
function swipeVideoL() {
	var img = $('.video').find('.u_media');
	var curr_img = null;
	img.each(function(){
		if( !$(this).hasClass('hidden') ){
			curr_img = $(this)
		}
	});
	var id = curr_img.attr('id');
	var arr_id = id.split('_');
	var curr_id = arr_id[0];
	var curr_num = arr_id[1]*1;
	var next_num = curr_num-1;
	if(next_num<1  ) {
		next_num = img.length;
	}
	//alert('#'+curr_id+'_'+next_num+'_')
	$('#'+curr_id+'_'+next_num).removeClass('hidden').siblings('.u_media').addClass('hidden');
	$('#'+curr_id+'_'+next_num+'_').removeClass('hidden').siblings('.u_media_nav_name').addClass('hidden');
	//$('#'+curr_id+'_'+next_num).addClass('curr').siblings('.switch').removeClass('curr');
};
function swipeVideoR() {
	var img = $('.video').find('.u_media');
	var curr_img = null;
	img.each(function(){
		if( !$(this).hasClass('hidden') ){
			curr_img = $(this)
		}
	});
	var id = curr_img.attr('id');
	var arr_id = id.split('_');
	var curr_id = arr_id[0];
	var curr_num = arr_id[1]*1;
	var next_num = curr_num+1;
	if( $('#'+curr_id+'_'+next_num+'_').length<1 ) {
		next_num = 1;
	}
	
	//alert('#'+curr_id+'_'+next_num+'_')
	$('#'+curr_id+'_'+next_num).removeClass('hidden').siblings('.u_media').addClass('hidden');
	$('#'+curr_id+'_'+next_num+'_').removeClass('hidden').siblings('.u_media_nav_name').addClass('hidden');
	//$('#'+curr_id+'_'+next_num+'__').addClass('curr').siblings('.switch').removeClass('curr');
};
// ������ ����� �� ��������
function JScrollHeightOnce() {
	var h = $(window).height();
	var cat_head_t = $('.cat_head').offset().top;
	var cat_head_h = $('.cat_head').height();
	var Sh = h - (cat_head_t+cat_head_h) - 115 - 225;

	if (Sh<200) {
		$('.scroll-pane').css('height','400');
		$('#layout').css('height','auto');
	}
	else if (Sh>1000) {
		$('.scroll-pane').css('height',1000);
		$('#layout').css('height','auto');
	}
	else {
		$('.scroll-pane').css('height',Sh);
		$('#layout').css('height','auto');
	}
}
function JScrollHeightDouble() {
	var h = $('#layout').height();
	var cat_head_t = $('.cat_head').not('.hidden').offset().top;
	var cat_head_h = $('.cat_head').not('.hidden').height();
	var Sh = h - (cat_head_t+cat_head_h) - 315;
	
	if (Sh<200) {
		$('.scroll-pane').css({
			'height': 200,
			'width': 860
		});
		$('.jspContainer').css({
			'width': 860
		});
		$('.jspPane').css({
			'width': 844
		});
		$('#layout').css('height','auto');
	}
	else if (Sh>1000) {
		$('.scroll-pane').css({
			'height': 1000,
			'width': 860
		});
		$('.jspContainer').css({
			'width': 860
		});
		$('.jspPane').css({
			'width': 844
		});
		$('#layout').css('height','auto');
	}
	else {
		$('.scroll-pane').css({
			'height': Sh,
			'width': 860
		});
		$('.jspContainer').css({
			'width': 860
		});
		$('.jspPane').css({
			'width': 844
		});
		$('#layout').css('height',h);
	}
}



//////////////////////////////////////////////////////////////////////
//add comment
$('.new_comment_button').live('click', function(){
	var currentForm = $(this).parents('.new_comment_form');
	var currentCommentList = currentForm.parents('#content').find('.commentList').first();
	var currentCommentListPopup = currentForm.parents('.popup_data').find('.commentList');
	var currentChildCommentList = currentForm.parents('.child_comments').find('.commentList');
	
	currentForm.find('.new_comment_text').trigger('click');

	var text = currentForm.find('.new_comment_text').val();
	var parent_id = parseInt(currentForm.find('.new_comment_parent_id').val());
	
	var images = '';
	currentForm.find('.images').each(function (i,element) {
		images += ($(element).val()) + ',';
	});

	var videos = '';
	currentForm.find('.videos').each(function (i,element) {
		videos += ($(element).val()) + ',';
	});
	
	var musics = '';
	currentForm.find('.musics').each(function (i,element) {
		musics += ($(element).val()) + ',';
	});
	
	if(text || images || videos || musics){
		var url = currentForm.attr('action');// + '&text=' + text + '&images=' + images + '&videos=' + videos + '&musics=' + musics;
		
		var term = '{"images":"'+images+'", "text":"'+encodeURI(text)+'", "videos":"'+videos+'", "musics": "'+musics+'"}';
		var dataJson = $.parseJSON(term);

		$.ajax({
			type: 'POST',
			//dataType:'json',
			data: dataJson,
			url: url,
			success: function(html){
				if(parent_id){
					currentChildCommentList.append(html);
				} else {
					if(currentCommentList.length){
						if($('.newCommentAfter')[0]){
							currentCommentList.append(html);
						}else{
							currentCommentList.prepend(html);
						}
					}else{
						currentCommentListPopup.find('form').before(html);
					}
					
					var hrefMore = $('#more_comments').attr('rel');
					if(hrefMore){
						var from = hrefMore.indexOf( '&offset=' )+8;
						var offset = parseInt(hrefMore.substr(from, 5));
						var newRel = hrefMore.substr(0,from) + (offset+1) + hrefMore.substr(from + offset.toString().length);
						$('#more_comments').attr('rel', newRel);
					}
				}
				
				$('.new_comment_text').val('Ваше сообщение').css('height','auto');
				$('.attachment').html('');
			}
		});
	};
});

// copy comment
$('.copycomment').live('click', function(){
	if(!$(this).hasClass('copied')){
		var currentForm = $(this).parent('.copyme');
		var link = $(this);
		var text = currentForm.find('.copytext').val();
		var images = currentForm.find('.copyimage').val();
		var videos = currentForm.find('.copyvideo').val();
		var musics = currentForm.find('.copymusic').val();
		var from = currentForm.find('.copyfrom').val();
		var fromgroup = currentForm.find('.copyfromgroup').val();
		var fromevent = currentForm.find('.copyfromevent').val();
		
		if(text || images || videos || musics){
			var url = $(this).attr('href');
			
			var term = '{"images":"'+images+'", "text":"'+text+'", "videos":"'+videos+'", "musics": "'+musics+'", "from": "'+from+'", "fromgroup": "'+fromgroup+'", "fromevent": "'+fromevent+'"}';
			
			var dataJson = $.parseJSON(term);
			
			$.ajax({
				type: 'POST',
				data: dataJson,
				url: url,
				success: function(html){
					link.addClass('copied');					
					link.parent('.u_buzz_link_block').removeClass('hidden').show(0);
				}
			});
		};
	}
	return false;
});
//copy music
$('.copymusic').live('click', function(){
	if(!$(this).hasClass('copied')){
		var link = $(this);
		var url = $(this).attr('href');
		$.ajax({
			type: 'GET',
			url: url,
			success: function(html){
				link.addClass('copied').find('.cc').html('Аудиозапись добавленна');
				link.parent('.u_buzz_link_block').removeClass('hidden').show(0);
			}
		});
	};
	return false;
});

// delete comment
$('.comment_delete').live('click', function(){
	var parent_id = parseInt($(this).attr('rel'));

	if(!parent_id){
		html  = '<div class="u_buzz_item">';
	}else{
		html  = '<div class="u_buzz_item child_u_buzz_item">';
	}
	
	html += '		<center>';
	html += '			<span class="u_buzz_text">Удалить коментарий?</span>';
	html += '			<span class="u_buzz_comment_link">';
	html += '				<a href="' + $(this).attr('href') + '" class="comment_confirm_delete" rel="' + parent_id + '" onclick="return false;">Да</a>';
	html += '				<a href="' + $(this).attr('href') + '" class="comment_restore" rel="' + parent_id + '" onclick="return false;">Нет</a>';
	html += '			</span>';
	html += '		</center>';
	html += '	</div>';	
	
	if(!parent_id){
		$(this).parents(".u_buzz_item").addClass('hidden');
		$(this).parents(".u_buzz_item").before(html);
	}else{
		$(this).parents(".child_u_buzz_item").addClass('hidden');
		$(this).parents(".child_u_buzz_item").before(html);
	}
});


$('.comment_confirm_delete').live('click', function(){
	var current = $(this);
	var currentCommentList = $(this).parents('.commentList');
	var parent_id = parseInt($(this).attr('rel'));

	$.ajax({
		type: 'GET',
		dataType:'json',
		url: current.attr('href'),
		success: function(json){
			if(!parent_id){
				current.parents(".u_buzz_item").remove();
			
				var hrefMore = $('#more_comments').attr('rel');
				if(hrefMore){
					var from = hrefMore.indexOf( '&offset=' )+8;
	
					var offset = parseInt(hrefMore.substr(from, 5));
					
					var newRel = hrefMore.substr(0,from) + (offset-1) + hrefMore.substr(from + offset.toString().length);
					
					$('#more_comments').attr('rel', newRel);	
				}
			}else{
				current.parents(".child_u_buzz_item").remove();
			}		
		}
	});
});


$('.comment_restore').live('click', function(){
	var parent_id = parseInt($(this).attr('rel'));
	
	if(!parent_id){
		$(this).parents(".u_buzz_item").next(".u_buzz_item").removeClass('hidden');
		$(this).parents(".u_buzz_item").remove();
	}else{
		$(this).parents(".child_u_buzz_item").next(".child_u_buzz_item").removeClass('hidden');
		$(this).parents(".child_u_buzz_item").remove();
	}	
});


// comment like|dislike
$('.comment_like').live('click', function(){
	var current = $(this);

	$.ajax({
		type: 'GET',
		dataType:'json',
		url: current.attr('href'),

		success: function(json){
			var countLikes = parseInt(current.find(".like_num").html());
			current.find(".like_num").html(countLikes+1);
			current.removeClass('comment_like');
			current.addClass('comment_dislike');
			current.attr('href', json['href_dislike']);
		}
	});
});


$('.comment_dislike').live('click', function(){
	var current = $(this);

	$.ajax({
		type: 'GET',
		dataType:'json',
		url: current.attr('href'),

		success: function(json){
			var countLikes = parseInt(current.find(".like_num").html());
			current.find(".like_num").html(countLikes-1);
			current.removeClass('comment_dislike');
			current.addClass('comment_like');
			current.attr('href', json['href_like']);
		}
	});
});


// more comments
$('#more_comments').live('click', function(){
	var current = $(this);

	$.ajax({
		type: 'GET',
		dataType:'html',
		url: current.attr('rel'),

		success: function(html){
			current.parents(".ovh").before(html);
			current.parents(".ovh").remove();
		}
	});
});


$('.more_child_comments').live('click', function(){
	$(this).parents('.child_comments').find('.child_u_buzz_item').removeClass('hidden');
	$(this).parents('.child_comments').find('.ovh').remove();
});


// new child comment
$('.new_child_comment').live('click', function(){
	$(this).parents('.u_buzz_item').find('.child_comments').removeClass('hidden');
	$(this).remove();
});


// change status
$('#user_status').live('click', function(){
	$('.new_status_form').removeClass('hidden');
	$(this).parent().addClass('hidden');
});


$('#new_status_button').live('click', function(){
	var status = $('.user_status_fld').val();
	var term = '{"status":"'+status+'"}';
	var dataJson = $.parseJSON(term);
	
	$.ajax({
		type: 'POST',
		data: dataJson,
		url: $('#status_form').attr('action'),
		success: function(html){
			if(status){
				$('.new_status_form').addClass('hidden');
				$('.new_status_form.old').removeClass('hidden');
				//$('#user_status').removeClass('hidden');
				$('#user_status').text(status);
			}
		}
	});
	return false;
});
$('#status_form').live('submit', function(){
	return false;
});
//save video
$('.save_video').live('click', function(){
	var el = $(this);
	$.ajax({
		type: 'GET',
		dataType:'html',
		url: el.attr('href'),
		success: function(html){
			el.parent().text('Видео добавлено!');
		}
	});
	return false;
});

//add attachment to comment
$('.add_attachment_to_comment').live('click', function(){
	var current = $(this);
	
	$.ajax({
		type: 'GET',
		dataType:'html',
		url: current.attr('rel'),

		success: function(html){
			if(current.parents('.child_comments')[0]){
				current.parents('.child_comments').find('.attachment').append('<div class="current_attachment"></div>');
			}else{
				current.parents('.u_buzz').find('.attachment').append('<div class="current_attachment"></div>');
			}
			
			$('#popup .popup_reduser').html(html);
			
			var h = $('body').height();
			$('.popup_content img').css({'max-height' : h-150});
			$('#popup').removeClass('hidden');
			$('body').css('overflow','hidden');
			if(h>$('#popup #fade').height()){$('#popup').addClass('allScreen')}
		}
	});
});

$('.add_attachment').live('click', function(){
	$('.current_attachment').after($(this).html());
	$('.current_attachment').remove();
	
	$('.image_x_wrap').removeClass('hidden');
	
	$('#popup').addClass('hidden');
	$('#popup .popup_reduser .popup_body').remove();
	$('body').css('overflow','auto');
});

$('.image_x').live('click', function(){
	$(this).parents('.one_image').remove();
});


//delete dialog
$('.delete_dialog').live('click', function(){

	html  = '	<div class="f_dialog_item">';
	html += '		<center>';
	html += '			<span class="u_buzz_text">Удалить диалог?</span>';
	html += '			<span class="u_buzz_comment_link">';
	html += '				<a href="' + $(this).attr('href') + '" class="dialog_confirm_delete" onclick="return false;">Да</a>';
	html += '				<a href="' + $(this).attr('href') + '" class="dialog_restore" onclick="return false;">Нет</a>';
	html += '			</span>';
	html += '		</center>';
	html += '	</div>';	
	
	$(this).parents(".f_dialog_item").addClass('hidden');
	$(this).parents(".f_dialog_item").before(html);
});


$('.dialog_confirm_delete').live('click', function(){
	var current = $(this);
	
	$.ajax({
		type: 'GET',
		dataType:'json',
		url: current.attr('href'),

		success: function(json){
			$(this).parents(".f_dialog_item").next(".f_dialog_item").remove();
			current.parents(".f_dialog_item").remove();
			
			JScrollHeightOnce();
			jQuery(function(){	
				$('.scroll-pane').jScrollPane({
					contentWidth: '0px',
					verticalGutter: 0
				});
			});			
		}
	});
});


$('.dialog_restore').live('click', function(){
	$(this).parents(".f_dialog_item").next(".f_dialog_item").removeClass('hidden');
	$(this).parents(".f_dialog_item").remove();	
});


// delete Messege
$('.delete_message').live('click', function(){

	html  = '	<div class="f_dialog_item white">';
	html += '		<center>';
	html += '			<span class="u_buzz_text">Удалить сообщение?</span>';
	html += '			<span class="u_buzz_comment_link">';
	html += '				<a href="' + $(this).attr('href') + '" class="message_confirm_delete" onclick="return false;">Да</a>';
	html += '				<a href="' + $(this).attr('href') + '" class="message_restore" onclick="return false;">Нет</a>';
	html += '			</span>';
	html += '		</center>';
	html += '	</div>';	
	
	$(this).parents(".f_dialog_item").addClass('hidden');
	$(this).parents(".f_dialog_item").before(html);
});


$('.message_confirm_delete').live('click', function(){
	var current = $(this);
	
	$.ajax({
		type: 'GET',
		dataType:'json',
		url: current.attr('href'),

		success: function(json){
			$(this).parents(".f_dialog_item").next(".f_dialog_item").remove();
			current.parents(".f_dialog_item").remove();
			
			JScrollHeightOnce();
			jQuery(function(){	
				$('.scroll-pane').jScrollPane({
					contentWidth: '0px',
					verticalGutter: 0
				});
			});			
		}
	});
});


$('.message_restore').live('click', function(){
	$(this).parents(".f_dialog_item").next(".f_dialog_item").removeClass('hidden');
	$(this).parents(".f_dialog_item").remove();	
});

//add message
$('#new_message_button').live('click', function(){
	var currentForm = $(this).parents('#buzz_message');

	currentForm.find('#new_message_text').trigger('click');

	var text = currentForm.find('#new_message_text').val();
	var companion = currentForm.find('#companion_id').val();
		
	var images = '';
	currentForm.find('.images').each(function (i,element) {
		images += ($(element).val()) + ',';
	});

	var videos = '';
	currentForm.find('.videos').each(function (i,element) {
		videos += ($(element).val()) + ',';
	});
	
	var musics = '';
	currentForm.find('.musics').each(function (i,element) {
		musics += ($(element).val()) + ',';
	});
	
	if((text || images || videos || musics) && companion){
		var url = currentForm.attr('action');
		
		var term = '{"images":"'+images+'", "companion":"'+companion+'", "text":"'+encodeURI(text)+'", "videos":"'+videos+'", "musics": "'+musics+'"}';
		var dataJson = $.parseJSON(term);
		
		$.ajax({
			type: 'POST',
			data: dataJson,
			url: url,
			success: function(html){
				if(currentForm.parents('#create_message_form')[0]){ 
					//window.location.replace(currentForm.parents('#create_message_form').find('#redirect').val() + '&companion=' + currentForm.parents('#create_message_form').find('#companion_id').val());
					var href = currentForm.parents('#create_message_form').find('#redirect').val() + /*'/' + */currentForm.parents('#create_message_form').find('#companion_id').val();
					//window.location.replace(href);
					$('#backBtn').attr('href', window.location.hash.substring(1)).show(0);
					if(href=='#' || href==''){
						href='/';
					}
					$.ajax({
						url: href,
						dataType: "html",
						context: document.body,
						beforeSend: function (  ) {
						    //$('.loading').show(0);
						},
						data: "ajax=true",
						type: "GET",
						success: function(data) {
							var content = data.match(/<div id="layout"[^>]*>([\w|\W]*)<\/div>/im);
						    $("#layout").empty().append($(content[1]));
						    $('#popup').addClass('hidden');
							$('#popup .popup_reduser .popup_body').remove();
							$('body').css('overflow','auto');
							$('.current_attachment').remove();
							window.location.hash = href;
							$(document).scrollTop(0);
							initAutocomplete();
							//$('.loading').hide(0);
						}
					});
					return false;
				}else{
					$('#u_search_tab2_').find('.scroll_block').append(html);
					
					JScrollHeightOnce();
					jQuery(function(){	
						$('.scroll-pane').jScrollPane({
							contentWidth: '0px',
							verticalGutter: 0
						});
						$('.scroll-pane').data('jsp').scrollTo(0, parseInt($('.jspPane').height()));
					});					
				}	

				$('#new_message_text').val('Ваше сообщение');
				$('.attachment').html('');
			}
		});
	}
});



// check message
$(document).ready(function() {
	startCheckMessage();
	startCheckRequestFriend();
});

function startCheckMessage(){
	$.ajax({
		type: 'GET',
		dataType:'json',
		url: $('#check_new_message').attr('rel'),
		success: function(count_messages){
			var currentInt = parseInt($('#check_new_message').next('.user_action_item_new').text());
			
			if(count_messages){
				$('#check_new_message').next('.user_action_item_new').text('+' + count_messages);
				$('#check_new_message').next('.user_action_item_new').next('.user_action_item_tooltip').find('.cc').text(count_messages + ' новых сообщений');
				$('#check_new_message').next('.user_action_item_new').removeClass('hidden');	
			
				if(currentInt != count_messages){
					if($('.message_form_add #companion_id').val()){
						$.ajax({
							type: 'GET',
							dataType:'html',
							url: $('#companion_id').attr('rel'),
							success: function(html){
								$('#messageListBlock').html(html);
								JScrollHeightOnce();
								jQuery(function(){	
									$('.scroll-pane').jScrollPane({
										contentWidth: '0px',
										verticalGutter: 0
									});
								});
								$('.scroll-pane').data('jsp').scrollTo(0, parseInt($('.jspPane').height()));
							}
						});	
					}
					
					$.ajax({
						type: 'GET',
						dataType:'json',
						url: $('#check_new_dialog').attr('rel'),
						success: function(count_dialog){
							$('#check_new_dialog').next('.user_action_item_new').text('+' + count_dialog);
							$('#check_new_dialog').next('.user_action_item_new').next('.user_action_item_tooltip').find('.cc').text(count_dialog + ' новых диалогов');
							$('#check_new_dialog').next('.user_action_item_new').removeClass('hidden');	
									
							if(!count_dialog){
								$('#check_new_dialog').next('.user_action_item_new').addClass('hidden');
								$('#check_new_dialog').next('.user_action_item_new').text('Нет новых диалогов');
							}										
						}
					});
								
				}
			}else{
				$('#check_new_message').next('.user_action_item_new').addClass('hidden');
				$('#check_new_message').next('.user_action_item_new').text('Нет новых сообщений');
			}
		}
	});	
	
	setTimeout("startCheckMessage()", 5000);
}

function startCheckRequestFriend(){
	$.ajax({
		type: 'GET',
		dataType:'json',
		url: $('#check_request_friend').attr('rel'),
		success: function(count_friends){
			if(parseInt(count_friends)){
				$('#check_request_friend').next('.user_action_item_new').text('+' + count_friends);
				$('#check_request_friend').next('.user_action_item_new').next('.user_action_item_tooltip').find('.cc').text(count_friends + ' запросов на дружбу');
				$('#check_request_friend').next('.user_action_item_new').removeClass('hidden');		
			}else{
				$('#check_request_friend').next('.user_action_item_new').addClass('hidden');
				$('#check_request_friend').next('.user_action_item_new').text('Нет запросов на дружбу');
			}
		}
	});	
	
	setTimeout("startCheckRequestFriend()", 5000);
}

// redirect to dialog
$('.href_dialog').live('click', function(){
	window.location.replace($(this).attr('rel'));
});

//autocomplete friends
$(document).ready(function() {
	initAutocomplete();
});
function initAutocomplete(){
	$('#create_message_form .search_friend').autocomplete({
		delay: 0,
		source: function(request, response) {
			$.ajax({
				url: $('#create_message_form .search_friend').attr('rel') + '?filter_name=' +  encodeURIComponent(request.term),
				dataType: 'json',
				success: function(json) {		
					response($.map(json, function(item) {
						return {
							label: item.full_name,
							value: item.friend_id
						}
					}));
				}
			});
		}, 
		select: function(event, ui) {
			//window.location.replace($('#friend_search_form').find('#redirect_getdialog').val() + '&companion=' + ui.item.value);
			var href = $('#create_message_form').find('#redirect').val() + '&companion=' + ui.item.value;
			$('#backBtn').attr('href', window.location.hash.substring(1)).show(0);
			if(href=='#' || href==''){
				href='/';
			}
			$.ajax({
				url: href,
				dataType: "html",
				context: document.body,
				beforeSend: function (  ) {
				    //$('.loading').show(0);
				},
				data: "ajax=true",
				type: "GET",
				success: function(data) {
					var content = data.match(/<div id="layout"[^>]*>([\w|\W]*)<\/div>/im);
				    $("#layout").empty().append($(content[1]));
				    $('#popup').addClass('hidden');
					$('#popup .popup_reduser .popup_body').remove();
					$('body').css('overflow','auto');
					$('.current_attachment').remove();
					window.location.hash = href;
					$(document).scrollTop(0);
					initAutocomplete();
					//$('.loading').hide(0);
				}
			});
			return false;
		}
	});
	
	$('#friend_search_form .search_friend').autocomplete({
		delay: 0,
		source: function(request, response) {
			$.ajax({
				url: $('#friend_search_form .search_friend').attr('rel') + '?filter_name=' +  encodeURIComponent(request.term),
				dataType: 'json',
				success: function(json) {						
					response($.map(json, function(item) {
						return {
							label: item.full_name,
							value: item.friend_id
						}
					}));
				}
			});
		}, 
		select: function(event, ui) {
			//window.location.replace($('#friend_search_form').find('#redirect_getdialog').val() + '&companion=' + ui.item.value);
			var href = $('#friend_search_form').find('#redirect_getdialog').val() + '&companion=' + ui.item.value;
			$('#backBtn').attr('href', window.location.hash.substring(1)).show(0);
			if(href=='#' || href==''){
				href='/';
			}
			$.ajax({
				url: href,
				dataType: "html",
				context: document.body,
				beforeSend: function (  ) {
				    //$('.loading').show(0);
				},
				data: "ajax=true",
				type: "GET",
				success: function(data) {
					var content = data.match(/<div id="layout"[^>]*>([\w|\W]*)<\/div>/im);
				    $("#layout").empty().append($(content[1]));
				    $('#popup').addClass('hidden');
					$('#popup .popup_reduser .popup_body').remove();
					$('body').css('overflow','auto');
					$('.current_attachment').remove();
					window.location.hash = href;
					$(document).scrollTop(0);
					initAutocomplete();
					//$('.loading').hide(0);
				}
			});
			return false;
		}
	});	
}

// search
$('#filter_country, #filter_love_status, #filter_age_from, #filter_age_to').live('change', function(){
	var current = $(this);
	var currentBlock = current.parents('.filter_block');
	
	var url = $(this).parents('form').attr('action') + '&text=' + $('#search_text').val();
	
	if(currentBlock.find('#filter_country')[0]){
		url += '&filter_country=' + currentBlock.find('#filter_country').val();
	}
	
	if(currentBlock.find('#filter_city')[0]){
		url += '&filter_city=' + currentBlock.find('#filter_city').val();
	}
	
	if(currentBlock.find('#filter_teach')[0]){
		url += '&filter_teach=' + currentBlock.find('#filter_teach').val();
	}	
	
	if(currentBlock.find('#filter_work')[0]){
		url += '&filter_work=' + currentBlock.find('#filter_work').val();
	}	
	
	if(currentBlock.find('#filter_work')[0]){
		url += '&filter_work=' + currentBlock.find('#filter_work').val();
	}		
	
	if(currentBlock.find('#filter_love_status')[0]){
		url += '&filter_love_status=' + currentBlock.find('#filter_love_status').val();
	}	
	
	if(currentBlock.find('#filter_age_to')[0]){
		url += '&filter_age_to=' + currentBlock.find('#filter_age_to').val();
	}	
	
	if(currentBlock.find('.filter_sex:checked')[0]){
		url += '&filter_sex=' + currentBlock.find('.filter_sex:checked').val();
	}	
	
	if(currentBlock.find('.filter_group_type:checked')[0]){
		url += '&filter_group_type=' + currentBlock.find('.filter_group_type:checked').val();
	}	

	$.ajax({
		url: url,
		dataType: 'html',
		success: function(html) {	
			currentBlock.find('.serchList').html(html);
		}
	});	
});

$('.filter_sex_click, .filter_group_type_click').live('click', function(){
	var current = $(this);
	var currentBlock = current.parents('.filter_block');
	
	var url = $(this).parents('form').attr('action') + '&text=' + $('#search_text').val();
	
	if(currentBlock.find('#filter_country')[0]){
		url += '&filter_country=' + currentBlock.find('#filter_country').val();
	}
	
	if(currentBlock.find('#filter_city')[0]){
		url += '&filter_city=' + currentBlock.find('#filter_city').val();
	}	
	
	if(currentBlock.find('#filter_teach')[0]){
		url += '&filter_teach=' + currentBlock.find('#filter_teach').val();
	}	
	
	if(currentBlock.find('#filter_work')[0]){
		url += '&filter_work=' + currentBlock.find('#filter_work').val();
	}	
	
	if(currentBlock.find('#filter_love_status')[0]){
		url += '&filter_love_status=' + currentBlock.find('#filter_love_status').val();
	}	
	
	if(currentBlock.find('#filter_age_from')[0]){
		url += '&filter_age_from=' + currentBlock.find('#filter_age_from').val();
	}	
	
	if(currentBlock.find('#filter_age_to')[0]){
		url += '&filter_age_to=' + currentBlock.find('#filter_age_to').val();
	}	
	
	if(currentBlock.find('.filter_sex:checked')[0]){
		url += '&filter_sex=' + currentBlock.find('.filter_sex:checked').val();
	}

	if(currentBlock.find('.filter_group_type:checked')[0]){
		url += '&filter_group_type=' + currentBlock.find('.filter_group_type:checked').val();
	}
	
	$.ajax({
		url: url,
		dataType: 'html',
		success: function(html) {	
			currentBlock.find('.serchList').html(html);
		}
	});	
});

$('.more_search').live('click', function(){
	var current = $(this);
	var currentBlock = current.parents('.filter_block');	
	
	var url = $(this).attr('rel') + '&text=' + $('#search_text').val();
	
	if(currentBlock.find('#filter_country')[0]){
		url += '&filter_country=' + currentBlock.find('#filter_country').val();
	}
	
	if(currentBlock.find('#filter_city')[0]){
		url += '&filter_city=' + currentBlock.find('#filter_city').val();
	}		

	if(currentBlock.find('#filter_teach')[0]){
		url += '&filter_teach=' + currentBlock.find('#filter_teach').val();
	}		
	
	if(currentBlock.find('#filter_work')[0]){
		url += '&filter_work=' + currentBlock.find('#filter_work').val();
	}		

	if(currentBlock.find('#filter_love_status')[0]){
		url += '&filter_love_status=' + currentBlock.find('#filter_love_status').val();
	}	
		
	if(currentBlock.find('#filter_age_from')[0]){
		url += '&filter_age_from=' + currentBlock.find('#filter_age_from').val();
	}	
	
	if(currentBlock.find('#filter_age_to')[0]){
		url += '&filter_age_to=' + currentBlock.find('#filter_age_to').val();
	}	
	
	if(currentBlock.find('.filter_sex:checked')[0]){
		url += '&filter_sex=' + currentBlock.find('.filter_sex:checked').val();
	}

	if(currentBlock.find('.filter_group_type:checked')[0]){
		url += '&filter_group_type=' + currentBlock.find('.filter_group_type:checked').val();
	}
	
	$.ajax({
		url: url,
		dataType: 'html',
		success: function(html) {	
			current.parents('.ovh').before(html);
			current.parents('.ovh').remove();
		}
	});		
});

$('#search_text').live('keyup', function(){
	var url = $('.filter').attr('action') + '&text=' + $(this).val();

	if($('.filter_block').find('#filter_country')[0]){
		url += '&filter_country=' + $('.filter_block').find('#filter_country').val();
	}
	
	if($('.filter_block').find('#filter_city')[0]){
		url += '&filter_city=' + $('.filter_block').find('#filter_city').val();
	}		

	if($('.filter_block').find('#filter_teach')[0]){
		url += '&filter_teach=' + $('.filter_block').find('#filter_teach').val();
	}	
	
	if($('.filter_block').find('#filter_work')[0]){
		url += '&filter_work=' + $('.filter_block').find('#filter_work').val();
	}	
	
	if($('.filter_block').find('#filter_love_status')[0]){
		url += '&filter_love_status=' + $('.filter_block').find('#filter_love_status').val();
	}	
		
	if($('.filter_block').find('#filter_age_from')[0]){
		url += '&filter_age_from=' + $('.filter_block').find('#filter_age_from').val();
	}	
	
	if($('.filter_block').find('#filter_age_to')[0]){
		url += '&filter_age_to=' + $('.filter_block').find('#filter_age_to').val();
	}	
	
	if($('.filter_block').find('.filter_sex:checked')[0]){
		url += '&filter_sex=' + $('.filter_block').find('.filter_sex:checked').val();
	}

	if($('.filter_block').find('.filter_group_type:checked')[0]){
		url += '&filter_group_type=' + $('.filter_block').find('.filter_group_type:checked').val();
	}	
	
	$.ajax({
		url: url,
		dataType: 'html',
		success: function(html) {	
			$('.serchList').html(html);
		}
	});		
});

$('#filter_city, #filter_teach, #filter_work').live('keyup', function(){
	var current = $(this);
	var currentBlock = current.parents('.filter_block');	
	
	var url = $(this).parents('form').attr('action') + '&text=' + $('#search_text').val();
	
	if(currentBlock.find('#filter_country')[0]){
		url += '&filter_country=' + currentBlock.find('#filter_country').val();
	}
	
	if(currentBlock.find('#filter_city')[0]){
		url += '&filter_city=' + currentBlock.find('#filter_city').val();
	}		
	
	if(currentBlock.find('#filter_teach')[0]){
		url += '&filter_teach=' + currentBlock.find('#filter_teach').val();
	}		
	
	if(currentBlock.find('#filter_work')[0]){
		url += '&filter_work=' + currentBlock.find('#filter_work').val();
	}			

	if(currentBlock.find('#filter_love_status')[0]){
		url += '&filter_love_status=' + currentBlock.find('#filter_love_status').val();
	}	
		
	if(currentBlock.find('#filter_age_from')[0]){
		url += '&filter_age_from=' + currentBlock.find('#filter_age_from').val();
	}	
	
	if(currentBlock.find('#filter_age_to')[0]){
		url += '&filter_age_to=' + currentBlock.find('#filter_age_to').val();
	}	
	
	if(currentBlock.find('.filter_sex:checked')[0]){
		url += '&filter_sex=' + currentBlock.find('.filter_sex:checked').val();
	}

	if(currentBlock.find('.filter_group_type:checked')[0]){
		url += '&filter_group_type=' + currentBlock.find('.filter_group_type:checked').val();
	}
	
	$.ajax({
		url: url,
		dataType: 'html',
		success: function(html) {	
			$('.serchList').html(html);
		}
	});		
});

// friends
$('.delete_friend').live('click', function(){

	html  = '	<div class="f_list_item">';
	html += '		<center>';
	html += '			<span class="u_buzz_text">Удалить друга?</span>';
	html += '			<span class="u_buzz_comment_link">';
	html += '				<a href="' + $(this).attr('href') + '" class="friend_confirm_delete" onclick="return false;">Да</a>';
	html += '				<a href="' + $(this).attr('href') + '" class="friend_restore" onclick="return false;">Нет</a>';
	html += '			</span>';
	html += '		</center>';
	html += '	</div>';	
	
	$(this).parents(".f_list_item").addClass('hidden');
	$(this).parents(".f_list_item").before(html);
});


$('.friend_confirm_delete').live('click', function(){
	var current = $(this);
	
	$.ajax({
		type: 'GET',
		dataType:'json',
		url: current.attr('href'),

		success: function(json){			
			$(this).parents(".f_list_item").next(".f_list_item").remove();
			current.parents(".f_list_item").remove();

			var hrefMore = $('.more_search').attr('rel');
			if(hrefMore){
				var from = hrefMore.indexOf( '&offset=' )+8;

				var offset = parseInt(hrefMore.substr(from, 5));
				
				var newRel = hrefMore.substr(0,from) + (offset-1) + hrefMore.substr(from + offset.toString().length);
				
				$('.more_search').attr('rel', newRel);	
			}			
		}
	});
});


$('.friend_restore').live('click', function(){
	$(this).parents(".f_list_item").next(".f_list_item").removeClass('hidden');
	$(this).parents(".f_list_item").remove();	
});


$('.confirm_friend').live('click', function(){
	var current = $(this);
	
	$.ajax({
		type: 'GET',
		dataType:'json',
		url: current.attr('href'),

		success: function(json){			
			var newCount = parseInt(current.parents("#u_friends_tab3_").find('.cat_head_h_txt span').text()) - 1;
			
			current.parents("#u_friends_tab3_").find('.cat_head_h_txt span').text(newCount);
			
			current.parents(".f_list_item").remove();
		}
	});
});

$('.new_child_comment_text').live('focus', function(){
	$(this).parents(".child_comments").find('.buzz_action').removeClass('hidden');
	$(this).css('height', '58');
});